﻿using System;
using System.Collections.Generic;
using System.Text;
using HtmlAgilityPack;
using System.Collections;
using System.Text.RegularExpressions;

namespace ihongma.WebData
{
   public static class HtmlHlep
    {
        #region IhtmlDocument 成员

       public static List<Model.UrlAge> htmllist(string html, string id, string Rules)
        {
            //HtmlAgilityPack.HtmlWeb web = new HtmlWeb();
          
            List<Model.UrlAge> list = new List<Model.UrlAge>();
            //string str = "";
          
            HtmlDocument dfsa = new HtmlDocument();
            //string html = HttpRequestHelper.GetPageSourceByUrl("http://www.open-open.com/ajax/", "utf-8");
            dfsa.LoadHtml(html);
            HtmlNode hn = dfsa.GetElementbyId(id);
           //hn=HtmlNode.CreateNode(HtmlSummary(hn.OuterHtml,hn.OuterHtml.Length));
            HtmlNodeCollection nodelist = hn.SelectNodes(Rules);
            HtmlNode temp = null;
            if (nodelist != null)
            {
                foreach (HtmlNode h in nodelist)
                {
                    Model.UrlAge age = new Model.UrlAge();
                    try
                    {


                        if (h.InnerText == "")
                        {
                            age.name = h.NextSibling.InnerText;
                            age.Url = h.NextSibling.Attributes["href"].Value;
                        }
                        else
                        {
                            temp = HtmlNode.CreateNode(h.OuterHtml);
                            age.name = temp.SelectSingleNode("//a").InnerText;
                            age.Url = temp.SelectSingleNode("//a").Attributes["href"].Value;
                        }
                        list.Add(age);
                    }
                    catch (Exception)
                    {


                    }
                    //HtmlNode temp = null;  
                    //str = str + text + href + "</br>";

                }
            }
            return list;
        }

       public static List<Model.UrlAge> htmlinfolist(string html, string id, string Rules)
       {
           List<Model.UrlAge> list = new List<Model.UrlAge>();
           //string str = "";
           HtmlDocument dfsa = new HtmlDocument();
           //string html = HttpRequestHelper.GetPageSourceByUrl("http://www.open-open.com/ajax/", "utf-8");
           dfsa.LoadHtml(html);
           HtmlNode hn = dfsa.GetElementbyId(id);
         
           //hn=HtmlNode.CreateNode(HtmlSummary(hn.OuterHtml,hn.OuterHtml.Length));
           HtmlNodeCollection nodelist = hn.SelectNodes(Rules);
           //HtmlNode temp = null;
           foreach (HtmlNode h in nodelist)
           {
               Model.UrlAge age = new Model.UrlAge();

               age.name = showinfo(h,"text");
               list.Add(age);
           }
           return list;
       }
       public static HtmlNodeCollection listHtml(HtmlNode hn, string rules)
       {
           HtmlNodeCollection nodelist = hn.SelectNodes(rules);
           return nodelist;
       }
       public static HtmlNodeCollection listhtml(string html, string xpath)
       {
           HtmlNode hn = HtmlNode.CreateNode(html);
           HtmlNodeCollection nodelist = hn.SelectNodes(xpath);
           return nodelist;
          
       }
       public static string showinfo(HtmlNode html, string str)
       {
           //HtmlNode html = temp.SelectSingleNode(rules);
           //Model.UrlAge age = new Model.UrlAge();
          string returnage = string.Empty;
                 if (html.OuterHtml=="")
                 {
                   
                     if (str == "text")
                         returnage = html.NextSibling.InnerText;
                     else
                         returnage = html.NextSibling.Attributes[str].Value;
                     //age.name = html.NextSibling.InnerText;
                     //age.Url = html.NextSibling.Attributes["href"].Value;
                 }
                 else
                 {
                     HtmlNode temp = HtmlNode.CreateNode(html.OuterHtml);
                         if(str=="text")
                     returnage= temp.InnerText;
                     else
                   returnage=temp.Attributes[str].Value;
                 }
                 return returnage;
       }

       public static string showinfo(string xpath, string str,string contet)
       {
           HtmlNodeCollection htomsdfsa = HtmlNode.CreateNode(contet).SelectNodes(xpath);
           HtmlNode htmls =HtmlNode.CreateNode(contet).SelectSingleNode(xpath);
           //HtmlNode html = temp.SelectSingleNode(rules);
           //Model.UrlAge age = new Model.UrlAge();
           string returnage ="";
           try
           {


               if (htmls != null)
               {
                   if (htmls.OuterHtml == "")
                   {

                       if (str == "text")
                           returnage = htmls.NextSibling.InnerText;
                       else
                           returnage = htmls.NextSibling.Attributes[str].Value;
                       //age.name = html.NextSibling.InnerText;
                       //age.Url = html.NextSibling.Attributes["href"].Value;
                   }
                   else
                   {
                       HtmlNode temp = HtmlNode.CreateNode(htmls.OuterHtml);
                       if (str == "text")
                           returnage = temp.InnerText;
                       else
                           returnage = temp.Attributes[str].Value;
                   }
               }
           }
           catch (Exception)
           {


           }
           return returnage;
       }
       public static HtmlNode getidinfo(string html, string id)
       {
           HtmlDocument dfsa = new HtmlDocument();
           dfsa.LoadHtml(html);
           //dfsa.LoadHtml(id);
           HtmlNode hn = dfsa.GetElementbyId(id);
           return hn;
       }
       public static HtmlNode gethtmlinfo(string xpath,HtmlNode hn)
       {
         
           //dfsa.LoadHtml(id);
           //HtmlNode htmo=new HtmlNode(;
           if (hn != null)
           {
               return hn.SelectSingleNode(xpath);
           }
           else
           {

               return hn;
           }
       }

       public static string FixHtml(string htmlString)
       {
           if (string.IsNullOrEmpty(htmlString)) return string.Empty;

           var hdoc = new HtmlDocument() { OptionWriteEmptyNodes = true };
           hdoc.LoadHtml(htmlString);
           return hdoc.DocumentNode.WriteTo();
       }

       public static string HtmlSummary(string content, int length)
       {
           //如果输入字符串长度小于截取长度，直接返回 
           if (content.Length <= length) return content;
           //如果输入字符串竟未包含html代码，那就直接截取 
           if (!content.Contains("<")) return content.Substring(0, length);
           //如果输入字符串中包含手动截取标记，则返回标记前的内容 
           if (content.Contains("<!-- summary end -->")) return Regex.Split(content, "<!-- summary end -->")[0];

           var IsTag = false; //当前字符是否在标签中 
           var Summary = String.Empty; //截取的子字符串 
           var TagName = String.Empty; //当前标签名称 
           var TagArray = new { Left = new ArrayList(), Right = new ArrayList() }; //左标签数组、右标签数组 

           content = FixHtml(content);

           foreach (var current in content)
           {
               if (length <= 0) break; //在截取长度>0的情况下，循环遍历html字符 

               if (current == '<') //当前字符为<，进入html标签 
               {
                   IsTag = true;
               }
               else if (current == '>') //当前字符为>，移出html标签 
               {
                   //如果当前标签名称以/开头，则此标签为闭合标签，应加入右标签数组 
                   if (TagName.Trim().StartsWith("/"))
                       TagArray.Right.Add(TagName);
                   //否则应加入左标签数组，但应考虑自闭合标签不加入闭合标签数组 
                   else if (!TagName.Trim().EndsWith("/") && !"img|br|input".Split('|')[0].Contains(TagName.ToLower()))
                       TagArray.Left.Add(TagName.Trim().ToLower().Split(' ')[0]);

                   IsTag = false; //标记已移出html标签 
                   TagName = String.Empty; //完成标签加入标签数组后，应重置此变量 
               }
               else
               {
                   if (IsTag) //如果在html标签中，则拼积当前标签名称 
                       TagName += current;
                   else //否则为纯文本内容，计数器开始自减，直到减为0，循环退出 
                       length--;
               }

               Summary += current; //拼积截取的子字符串 
           }

           Summary = Summary.Trim();

           //从左标签数组中移除已闭合的标签 
           //TagArray.Left.RemoveRange(0, TagArray.Right.Count); 
           while (TagArray.Right.Count > 0)
           {
               TagArray.Left.RemoveAt(TagArray.Left.IndexOf(TagArray.Right[0].ToString().Replace("/", "")));
               TagArray.Right.RemoveAt(0);
           }

           //剩余标签未闭合，逆序以html闭合标签格式拼接至截取的子字符串末尾 
           if (TagArray.Left.Count > 0)
               for (var i = TagArray.Left.Count - 1; i >= 0; i--)
               {
                   Summary += String.Format("</{0}>", TagArray.Left[i].ToString());
               }

           return Summary;
       }
        //public static T htmlInfo<T>(string html)
        //{
            
        //    throw new NotImplementedException();
        //}

        #endregion
    }
}
